<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        ul {
            list-style: none;
            margin: 0;
            padding: 0;
        }
        input{
            border: none;
            outline: none;
            border-radius: 4px;
            box-shadow: 0 0 0 1px #dcdfe6;
            box-sizing: border-box;
            font-size: 14px;
            line-height: 32px;
        }
        
        .btn {
            color: #fff;
            border-color: #79bbff;
            background-color: #409eff;
            outline: none;
            display: inline-flex;
            justify-content: center;
            align-items: center;
            line-height: 1;
            height: 32px;
            white-space: nowrap;
            cursor: pointer;
            text-align: center;
            box-sizing: border-box;
            transition: .1s;
            user-select: none;
            vertical-align: middle;
            border: 1px solid #dcdfe6;
            padding: 8px 15px;
            font-size: 14px;
            border-radius: 4px;
        }

        .red-btn {
            background-color: #f56c6c;
            border-color: #f56c6c;
        }

        .switch {
            display: inline-flex;
            align-items: center;
            position: relative;
            font-size: 14px;
            line-height: 20px;
            height: 32px;
            vertical-align: middle;
        }
        .switch-core {
            display: inline-flex;
            position: relative;
            align-items: center;
            min-width: 40px;
            height: 20px;
            border: 1px solid #dcdfe6;
            outline: none;
            border-radius: 10px;
            box-sizing: border-box;
            background: #dcdfe6;
            cursor: pointer;
            transition: border-color .3s, background-color .3s;
        }
        .switch-core .switch-action {
            position: absolute;
            left: 1px;
            border-radius: 100%;
            transition: all .3s;
            width: 16px;
            height: 16px;
            background-color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #dcdfe6;
        }

        .switch.is-checked .switch-core {
            border-color: #409eff;
            background-color: #409eff;
        }
        .switch.is-checked .switch-core .switch-action {
            left: calc(100% - 17px);
            color: #409eff;
        }

        .chatroom-list {
            display: flex;
        }

        .room-item {
            position: relative;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 120px;
            height: 120px;
            margin: 5px;
            border: 1px solid #dcdfe6;
            border-radius: 5px;
            cursor: pointer;
        }
        .room-item.ai-room ::before {
            content: 'AI';
            position: absolute;
            width: 30px;
            height: 16px;
            font-size: 12px;
            line-height: 16px;
            top: 0;
            left: 0;
            background: #00ff00;
            color: #fff;
            text-align: center;
        }

        .chat-room {
            display: none;
            width: 350px;
        }

        .chat-item {
            display: flex;
            align-items: center;
        }

        .chat-item .chat-time {
            /* display: none; */
            flex-shrink: 0;
            color: #666;
            font-size: 12px;
        }

        .chat-item .chat-msg {
            position: relative;
            margin: 0 10px;
            padding: 2px 5px;
        }

        .chat-item.self {
            justify-content: flex-end;
        }

        .chat-item.server {
            justify-content: center;
            font-style: italic;
            font-size: 12px;
        }

        .chat-item.user .chat-msg {
            background-color: #eee;
            border: 1px solid #dcdfe6;
            border-radius: 5px;
        }

        .chat-item.user .chat-msg::before {
            position: absolute;
            left: -10px;
            top: 2px;
            content: '';
            width: 0;
            height: 0;
            border-bottom: 10px solid #eee;
            border-left: 10px solid transparent;
        }

        .chat-item.self .chat-msg {
            background-color: #79bbff;
            border: 1px solid #409eff;
            color: #fff;
            border-radius: 5px;
        }

        .chat-item.self .chat-msg::before {
            position: absolute;
            right: -10px;
            top: 2px;
            content: '';
            width: 0;
            height: 0;
            border-bottom: 10px solid #79bbff;
            border-right: 10px solid transparent;
        }

        .chat-item .chat-user {
            flex-shrink: 0;
            text-align: center;
            line-height: 50px;
            width: 50px;
            height: 50px;
            border: 1px solid #eee;
            border-radius: 5px;
        }

        .chat-users {
            display: flex;
        }

        .chat-users .user-item {
            text-align: center;
            line-height: 30px;
            overflow: hidden;
            margin: 2px 5px;
            font-size: 12px;
            width: 30px;
            height: 30px;
            border: 1px solid #eee;
            border-radius: 5px;
        }

        .new-room-box {
            display: none;
        }
    </style>
</head>

<body>
    <div class="hall">
        <div class="userinfo">
            <label for="username">你的名字:</label><input id="username" type="text" value="张三" autocomplete="off">
        </div>
        <button class="new-chatroom btn">新建房间</button>
        <div class="new-room-box">
            <label for="roomname">房间名称:</label>
            <input id="roomname" type="text" value="" autocomplete="off">
            <label>
                是否添加AI
                <div class="is-ai switch">
                    <span class="switch-core">
                        <div class="switch-action"></div>
                    </span>
                </div>
            </label>
            <button class="new-chatroom-cancel btn red-btn">取消</button>
            <button class="new-chatroom-ok btn">确定</button>
        </div>
        <div class="chatroom-list">
        </div>
    </div>
    <div class="chat-room">
        <div class="room-name"></div>
        用户列表<div class="leave-btn btn red-btn">离开房间</div>
        <div class="chat-users">
        </div>
        <ul class="chat">
        </ul>
        <textarea class="textarea" name="" id="" cols="30" rows="10"></textarea>
        <div class="btn" id="slider">发送消息</div>
    </div>

    <script>
        // 消息列表
        let msgList = []
        // 房间列表
        let roomList = []
        // 用户列表
        let userList = []
        let ws = null
        // 房间是否添加ai
        let isAi = false
        WebSocketTest()
        function WebSocketTest() {
            console.log('%c浏览器支持websocket', 'background:#41b883;color:#fff;border-radius: 3px');
            if ("WebSocket" in window) {
                ws = new WebSocket("ws://127.0.0.1:8001/");
                ws.onopen = function () {
                    // 这里可以发送请求,先获取之前的列表数据
                    // Web Socket 已连接上，使用 send() 方法发送数据
                    console.log('连接 WebSocket');
                };

                ws.onmessage = function (evt) {
                    const data = JSON.parse(evt.data)
                    console.log(data);
                    if (data.type === 'room') {
                        // 房间数据
                        roomList = data.data
                        roomRender()
                    } else if (['server', 'usermsg', 'selfmsg'].includes(data.type)) {
                        // 消息
                        msgList.push(data)
                        chatRender()
                    } else if (data.type === 'userslist') {
                        // 用户列表更新
                        userList = data.data
                        usersRender()
                    } else if (data.type === 'roominfo') {
                        // 房间信息
                        document.querySelector('.room-name').innerHTML = data.data.name
                    }
                };

                ws.onclose = function () {
                    console.log('关闭 WebSocket');
                };
            }

            else {
                // 浏览器不支持 WebSocket
                console.log('浏览器不支持 WebSocket');
            }
        }

        // 发送消息事件
        const textarea = document.querySelector('.textarea')
        document.querySelector('#slider').addEventListener('click', () => {
            if (!textarea.value.length) return
            ws.send(JSON.stringify({
                type: 'usermsg',
                data: textarea.value,
                time: new Date().toLocaleString()
            }))
            textarea.value = ''
        })
        const chatBox = document.querySelector('.chat')
        // 渲染聊天列表
        const chatRender = () => {
            chatBox.innerHTML = msgList.map(item => {
                let htmlstr = ''
                if (item.type === 'usermsg') {
                    // 其他用户发送的消息
                    htmlstr = `<li class="chat-item user">
                        <span class="chat-user">${item.name}</span>
                        <span class="chat-msg">${item.data}</span>
                        <span class="chat-time">${item.time}</span>
                        </li>`
                } else if (item.type === 'selfmsg') {
                    // 自己发送的消息
                    htmlstr = `<li class="chat-item self">
                        <span class="chat-time">${item.time}</span>
                        <span class="chat-msg">${item.data}</span>
                        <span class="chat-user">${item.name}</span>
                        </li>`
                } else if (item.type === 'server') {
                    // 系统发送的消息
                    htmlstr = `<li class="chat-item server">
                        <span class="chat-time">${item.time}</span>
                        <span class="chat-msg">${item.data}</span>
                        </li>`
                }
                return htmlstr
            }).join('')
        }

        // 点击是否添加ai开关
        const isaiswitch = document.querySelector('.is-ai')
        isaiswitch.addEventListener('click', function() {
            this.classList.toggle('is-checked')
            isAi = !isAi
        })
        // 新建房间按钮点击事件
        const roomnameinput = document.querySelector('#roomname')
        document.querySelector('.new-chatroom').addEventListener('click', () => {
            document.querySelector('.new-room-box').style.display = "block"
        })
        // 新建房间确定按钮点击事件
        document.querySelector('.new-chatroom-ok').addEventListener('click', () => {
            if (roomnameinput.value === '') {
                roomnameinput.focus()
                return alert('请填写房间名称')
            }
            if (usernameinput.value === '') {
                usernameinput.focus()
                return alert('请填写你的名字')
            }
            ws.send(JSON.stringify({
                type: 'newroom',
                data: {
                    username: usernameinput.value,
                    roomName: roomnameinput.value,
                    isAi: isAi
                },
                time: new Date().toLocaleString()
            }))
            // 新建完成后进入房间
            document.querySelector('.hall').style.display = "none"
            document.querySelector('.chat-room').style.display = "block"
            document.querySelector('.new-room-box').style.display = "none"
            roomnameinput.value = ''
            isaiswitch.classList.remove('is-checked')
            isAi = false
        })
        // 新建房间取消按钮点击事件
        document.querySelector('.new-chatroom-cancel').addEventListener('click', () => {
            document.querySelector('.new-room-box').style.display = "none"
            roomnameinput.value = ''
            isaiswitch.classList.remove('is-checked')
            isAi = false
        })
        // 渲染房间列表
        const roomBox = document.querySelector('.chatroom-list')
        const roomRender = () => {
            let htmlStr = ''
            if(roomList.length) {
                htmlStr = roomList.map(item => `<div data-index="${item.id}" class="room-item${item.ai ? ' ai-room' : ''}">
                <div>房间号:${item.id}</div>
                <div>${item.name}</div>
                <div>${item.count}人</div>
                </div>`).join('')
            }else {
                htmlStr = '暂无房间,点击上方新建'
            }
            roomBox.innerHTML = htmlStr
        }
        // 用户名输入框
        const usernameinput = document.querySelector('#username')
        // 房间点击事件
        roomBox.addEventListener('click', e => {
            let roomItem = null
            for (let el = e.target; el !== e.currentTarget; el = el.parentElement) {
                if (el.className.indexOf('room-item') >= 0) {
                    roomItem = el
                    break
                }
            }
            console.log(roomItem);
            if (roomItem === null) return
            if (usernameinput.value === '') {
                usernameinput.focus()
                return alert('请填写你的名字')
            }
            ws.send(JSON.stringify({
                type: 'enterroom',
                data: {
                    username: usernameinput.value,
                    roomId: parseInt(roomItem.dataset.index)
                },
                time: new Date().toLocaleString()
            }))
            document.querySelector('.hall').style.display = "none"
            document.querySelector('.chat-room').style.display = "block"
        })

        // 渲染用户列表
        const usersBox = document.querySelector('.chat-users')
        const usersRender = () => {
            usersBox.innerHTML = userList.map(item => `<div class="user-item">${item}</div>`).join('')
        }

        // 离开房间事件
        document.querySelector('.leave-btn').addEventListener('click', () => {
            ws.send(JSON.stringify({
                type: 'leaveroom',
                time: new Date().toLocaleString()
            }))
            document.querySelector('.hall').style.display = "block"
            document.querySelector('.chat-room').style.display = "none"
            // 离开房间后清空聊天列表
            msgList = []
            chatRender()
        })
    </script>
</body>

</html>